package com.example.demo.handler;

import cn.hutool.core.util.ObjectUtil;
import com.example.demo.constant.SecurityConstant;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.RedisUtil;
import com.example.demo.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录成功处理器
 *登录成功后不跳转页面，返回json格式数据
 *
 * @author star
 */
@Component
@AllArgsConstructor
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private JwtUtil jwtUtil;
    private RedisUtil redisUtil;
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        String username = authentication.getName();
        String jwtToken = jwtUtil.create(username);
        //1.token的KEY 2.KEY里面存的键  3.存的值  4.过期时间
        redisUtil.hashSet(SecurityConstant.TOKEN_KEY,username,authentication,SecurityConstant.TOKEN_EXPIRE);
        response.getWriter().write(objectMapper.writeValueAsString(Result.ok(jwtToken,"登录成功")));
        //        redisUtil.hashSet(SecurityConstant.TOKEN_KEY, authentication.getName(), authentication, SecurityConstant.TOKEN_EXPIRE);
//        ResponseUtil.writeJson(response, objectMapper.writeValueAsString(Result.ok(jwtUtil.create(authentication.getName()), "登录成功")));
    }
}
